<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="1400px"
    append-to-body
    :before-close="cancel"
  >
    <el-tabs @tab-click="handleClick">
      <el-tab-pane label="普通商品入库" name="0">
        <el-form ref="form" :model="form" :rules="rules">
          <el-row>
            <el-col :span="7">
              <el-form-item label="供应商" prop="supplier">
                <el-select
                  ref="myselect"
                  v-model="form.supplier"
                  clearable
                  filterable
                  @change="updateSupplier"
                  placeholder="请选择供应商"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库日期" prop="createTime">
                <el-date-picker
                  v-model="form.createTime"
                  style="width: 205px"
                  type="datetime"
                  placeholder="选择日期时间"
                  clearable
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @input="changeTime($event)"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <div :style="{ display: 'flex' }">
            <span>随箱单：</span>
            <span>
              <el-upload
                ref="upload"
                style="width: 316px; margin-left: 6px; padding-bottom: 20px"
                class="upload-demo"
                multiple
                accept=".xlsx,.xls"
                :headers="upload.headers"
                :action="upload.url + '?goodsType=' + type"
                :before-remove="beforeRemove"
                :limit="1"
                :file-list="goodsList"
                :on-exceed="tishi"
                :on-progress="handleFileUploadProgress"
                :on-remove="handleRemove"
                :on-success="handleFileSuccess"
                :on-change="checkFileType"
              >
                <el-button v-hasPermi="['tms:warehouseIn:import']" size="small"
                  >点击上传</el-button
                >
                <span slot="tip" class="el-upload__tip" style="color: red">
                  (仅支持.xlsx/.xls的附件，且不超过10M)
                </span>
              </el-upload>
            </span>
            <span style="color: blue">
              <a
                href="http://img.mofankj.com/普通商品入库样例.xls"
                target="_blank"
                >普通商品入库的随箱单参考样例</a
              >
            </span>
          </div>
        </el-row>
        <el-row>
          <div
            :style="{
              'margin-left': '812px',
            }"
          >
            <span
              :style="{
                'margin-left': '33px',
                'font-weight': '700',
                color: 'red',
              }"
              >合计：{{ countSum }}</span
            >
          </div>
        </el-row>
        <el-table
          :header-cell-style="{ background: '#ADA9A9', color: '#000' }"
          :row-class-name="tableRowClassName"
          :data="goodsIn"
          :border="true"
        
        >
          <el-table-column label="序号" prop="id" width="55" align="center" />
          <el-table-column
            label="箱号"
            align="center"
            width="60"
            prop="packageNo"
          />
          <el-table-column
            label="包装"
            align="center"
            width="80"
            prop="packageType"
          />
          <el-table-column
            label="计划发货日期"
            width="110"
            align="center"
            prop="planDeliverData"
          />
          <el-table-column
            label="卡特需求日"
            width="110"
            align="center"
            prop="requireDate"
          />
          <el-table-column
            label="订单号"
            width="120"
            align="center"
            prop="orderNo"
          />
          <el-table-column
            label="零件号码"
            width="130"
            align="center"
            prop="goodsNo"
          />
          <el-table-column
            label="零件中文名称"
            width="120"
            align="center"
            prop="goodsName"
          />
          <el-table-column label="单位" width="60" align="center" prop="unit" />
          <el-table-column label="数量" align="center" prop="stock">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stock"
                placeholder="请输入内容"
                oninput="value=value.replace(/[^\d]/g,'')"
                @input="stockInput(scope.row.stock)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="毛重(公斤)"
            align="center"
            prop="grossWeight"
          />
          <el-table-column label="净重(公斤)" align="center" prop="netWeight" />
          <el-table-column label="长(厘米)" align="center" prop="length" />
          <el-table-column label="宽(厘米)" align="center" prop="width" />
          <el-table-column label="高(厘米)" align="center" prop="height" />
        </el-table>
        <el-row>
          <span
            :style="{
              'margin-left': '812px',
              'margin-bottom': '20px',
            }"
          >
            <span
              :style="{
                'margin-left': '20px',
                'font-weight': '700',
                color: 'red',
              }"
              >合计：{{ countSum }}</span
            >
          </span>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="驾驶室入库" name="1">
        <el-form ref="form" :model="form" :rules="rules">
          <el-row>
            <el-col :span="7">
              <el-form-item label="供应商" prop="supplier">
                <el-select
                  ref="myselect"
                  v-model="form.supplier"
                  clearable
                  filterable
                  @change="updateSupplier"
                  placeholder="请选择供应商"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库日期" prop="createTime">
                <el-date-picker
                  v-model="form.createTime"
                  style="width: 205px"
                  type="datetime"
                  placeholder="选择日期时间"
                  clearable
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @input="changeTime($event)"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <div :style="{ display: 'flex' }">
            <span>随箱单：</span>
            <span>
              <el-upload
                ref="upload"
                style="width: 316px; margin-left: 6px; padding-bottom: 20px"
                class="upload-demo"
                multiple
                accept=".xlsx,.xls"
                :headers="upload.headers"
                :action="upload.url + '?goodsType=' + type"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="tishi"
                :file-list="goodsList"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-change="checkFileType"
              >
                <el-button v-hasPermi="['tms:warehouseIn:import']" size="small"
                  >点击上传</el-button
                >
                <span slot="tip" class="el-upload__tip" style="color: red">
                  (仅支持.xlsx/.xls的附件，且不超过10M)
                </span>
              </el-upload>
            </span>
            <span style="color: blue">
              <a
                href="http://img.mofankj.com/驾驶室入库样例.xls"
                target="_blank"
                >驾驶室入库随箱单参考样例</a
              >
            </span>
          </div>
        </el-row>
        <el-row>
          <span
            :style="{
              'margin-left': '935px',
              'margin-bottom': '20px',
            }"
          >
            <span
              :style="{
                'margin-left': '33px',
                'font-weight': '700',
                color: 'red',
              }"
              >合计：{{ countSum }}</span
            >
          </span>
        </el-row>
        <el-table
          :header-cell-style="{ background: '#ADA9A9', color: '#000' }"
          :row-class-name="tableRowClassName"
          :data="goodsIn"
          :border="true"
        >
          <el-table-column label="序号" prop="id" width="50" align="center" />
          <el-table-column
            label="箱号"
            align="center"
            width="60"
            prop="packageNo"
          />
          <el-table-column
            label="包装"
            align="center"
            width="60"
            prop="packageType"
          />
          <el-table-column
            label="计划发货日期"
            width="100"
            align="center"
            prop="planDeliverData"
          />
          <el-table-column
            width="100"
            label="卡特需求日"
            align="center"
            prop="requireDate"
          />
          <el-table-column
            label="订单号"
            width="120"
            align="center"
            prop="orderNo"
          />
          <el-table-column
            label="系列号"
            width="150"
            align="center"
            prop="parentGoodsNo"
          />
          <el-table-column
            label="零件号码"
            width="150"
            align="center"
            prop="goodsNo"
          />
          <el-table-column
            label="零件中文名称"
            width="130"
            align="center"
            prop="goodsName"
          />
          <el-table-column label="单位" width="55" align="center" prop="unit" />
          <el-table-column label="数量" align="center" prop="stock">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stock"
                placeholder="请输入内容"
                oninput="value=value.replace(/[^\d]/g,'')"
                @input="stockInput(scope.row.stock)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="毛重(公斤)"
            width="80"
            align="center"
            prop="grossWeight"
          />
          <el-table-column
            width="80"
            label="净重(公斤)"
            align="center"
            prop="netWeight"
          />
          <el-table-column label="长(厘米)" align="center" prop="length" />
          <el-table-column label="宽(厘米)" align="center" prop="width" />
          <el-table-column label="高(厘米)" align="center" prop="height" />
        </el-table>
        <el-row>
          <span
            :style="{
              'margin-left': '935px',
              'margin-bottom': '20px',
            }"
          >
            <span
              :style="{
                'margin-left': '33px',
                'font-weight': '700',
                color: 'red',
              }"
              >合计：{{ countSum }}</span
            >
          </span>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary"  @click="submitForm"
        >确 定</el-button
      >
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from "@/utils/auth";
import { getQnToken } from "@/api/system/user";
import {
  transportIn,
  addGoods,
  saveGoods,
  getSupplier,
} from "@/api/tms/inventory";
export default {
  name: "AddWarehouseIn",
  props: {
    dialogVisible: Boolean,
    title: String,
  },
  data() {
    return {
      // loading: false,
      normalLoading: false,
      countSum: 0,
      supplierList: [],
      type: 0,
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "tms/goodsStockHistory/list_select_import_stock",
      },
      // 普通入库
      goodsList: [],
      // 导入配载单表格数据
      goodsIn: [],
      form: {},
      rules: {
        createTime: [
          { required: true, message: "请选择入库时间", trigger: "blur" },
        ],
        supplier: [
          { required: true, message: "请选择所属供应商", trigger: "blur" },
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      total: "",
    };
  },
  computed: {
    timeDefault() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      if (month < 10) {
        month = `0${month}`;
      } else {
        month = month;
      }
      let data = date.getDate();
      if (data < 10) {
        data = `0${data}`;
      } else {
        data = data;
      }
      let hours = date.getHours();
      if (hours < 10) {
        hours = `0${hours}`;
      } else {
        hours = hours;
      }
      let minutes = date.getMinutes();
      if (minutes < 10) {
        minutes = `0${minutes}`;
      } else {
        minutes = minutes;
      }
      let seconds = date.getSeconds();
      if (seconds < 10) {
        seconds = `0${seconds}`;
      } else {
        seconds = seconds;
      }
      let time =
        year +
        "-" +
        month +
        "-" +
        data +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      this.form.createTime = time;
      return time;
    },
  },
  mounted() {},
  watch: {
    dialogVisible(newVal) {
      if (newVal) {
        this.getSupplierList();
        this.form.createTime = this.timeDefault;
      }
    },
  },
  methods: {
    stockInput(val) {
      this.countSum = 0;
      for (let i = 0; i < this.goodsIn.length; i++) {
        let stock = Number(this.goodsIn[i].stock);
        this.countSum += stock;
      }
    },
    updateSupplier(val) {
      this.$nextTick(() => {
        // 强制更新
        this.$forceUpdate();
      });
      if (val) {
        this.$set(
          this.form,
          this.form.supplier,
          this.$refs.myselect.selected.label
        );
      } else {
        this.$set(this.form, this.form.supplier, "");
      }
    },
    getSupplierList() {
      getSupplier().then((res) => {
        this.supplierList = res.data;
      });
    },
    changeVal(e) {
      this.$forceUpdate();
    },
    changeTime(e) {
      this.$forceUpdate();
      this.form.createTime = e;
    },
    // 切换tab获取标识
    handleClick(tab) {
      this.type = tab.name;
      this.goodsIn = [];
      this.goodsList = [];
      this.form.supplier = "";
      this.form.createTime = this.timeDefault;
      this.countSum = 0;
    },
    huanchong() {
      this.normalLoading = this.$loading({
        lock: true,
        text: "拼命加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.goodsIn.length > 0) {
        this.form.supplier = this.$refs.myselect.selected.label;
      } else {
        this.form.supplier = this.form.supplier;
      }
      let params = {
        saveGoodsStockList: this.goodsIn,
        type: this.type,
        supplier: this.form.supplier,
        inOutDate: this.form.createTime,
      };
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.huanchong()
          // this.loading = true
          saveGoods(params).then((res) => {
            this.normalLoading.close()
            // this.loading = false
            if (res.code == 200) {
              this.huanchong()
              // this.loading = true
              addGoods(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.normalLoading.close()
                // this.loading = false
                this.$refs["form"].resetFields();
                this.$emit("refresh");
                this.goodsIn = [];
                this.goodsList = [];
                this.countSum = 0;
                this.form = {}
              });
            } else {
              return false;
            }
          });
        } else {
          this.$message.error("供应商或入库日期为空，请检查！");
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$emit("refresh");
      this.goodsIn = [];
      this.goodsList = [];
      this.form = {};
      clearTimeout();
      this.countSum = 0;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 500) {
        this.$message.error(`${response.msg}`);
        this.goodsList = [];
      }
      if (response.data.length <= 0) {
        this.$message.error("未解析到数据,请按规定上传!");
        this.goodsList = [];
      } else {
        this.goodsList.push({
          name: file.name,
        });
        this.goodsIn = response.data;
      }
      this.goodsIn.map((item) => {
        this.countSum += item.stock;
      });
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      for (let i = 0; i < this.goodsIn.length; i++) {
        this.goodsIn[i].id = i + 1;
      }
    },
    // 限制上传文件大小
    checkFileType(file) {
      // 1KB=1024B   1MB=1024KB   1GB=1024MB
      let fileSize = file.size / 1024 / 1024;
      if (fileSize > 10) {
        this.$message.error("上传文件不能超过10M!");
        this.normalLoading.close()
        this.goodsList = [];
        return false;
      }
    },
    // 移除文件
    handleRemove(file) {
      // 上传
      this.goodsList.forEach((value, index, array) => {
        if (file.url == value.url) {
          array.splice(index, 1);
          this.goodsIn = [];
          this.countSum = 0;
        }
      });
    },
    // 移除文件时的提示
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 上传文件超过指定个数时的提示信息
    tishi() {
      this.$message.warning("当前限制只可选择 1 个文件");
    },
    /** 获取七牛云token */
    getQnToken() {
      return new Promise((resolve, reject) => {
        getQnToken().then((response) => {
          resolve(response);
        });
      });
    },
    // 表单隔行变色
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "success-row";
      } else {
        return "warning-row";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table .warning-row {
  background: #f7faff;
}
.el-table .success-row {
  background: #ebf1fb;
}

::v-deep.el-tabs {
  .el-tabs__item {
    font-size: 14px;
  }
}
::v-deep .el-input--small .el-input__inner {
  color: #606266 !important;
}
::v-deep .el-input__inner {
  color: #606266 !important;
}
::v-deep .el-range-editor--small .el-range-input {
  color: #606266 !important;
}
</style>
